<%@ page contentType="text/html;charset=UTF-8" %>
<script>
$(document).ready(function() {
    $('#date').datetimepicker({
        format: "YYYY-MM-DD"
    })
	$('#procurementApplicationTable').bootstrapTable({
		 
		  //请求方法
               method: 'get',
        height:580,
               //类型json
               dataType: "json",
               //显示刷新按钮
               showRefresh: true,
               //显示切换手机试图按钮
               showToggle: true,
               //显示 内容列下拉框
    	       showColumns: true,
    	       //显示到处按钮
    	       showExport: true,
    	       //显示切换分页按钮
    	       showPaginationSwitch: true,
    	       //显示详情按钮
    	       detailView: true,
    	       	//显示详细内容函数
	           detailFormatter: "detailFormatter",
    	       //最低显示2行
    	       minimumCountColumns: 2,
               //是否显示行间隔色
               striped: true,
               //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）     
               cache: false,    
               //是否显示分页（*）  
               pagination: true,   
                //排序方式 
               sortOrder: "asc",  
               //初始化加载第一页，默认第一页
               pageNumber:1,   
               //每页的记录行数（*）   
               pageSize: 10,  
               //可供选择的每页的行数（*）    
               pageList: [10, 25, 50, 100],
               //这个接口需要处理bootstrap table传递的固定参数,并返回特定格式的json数据  
               url: "${ctx}/ap/procurementApplication/data",
               //默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
               //queryParamsType:'',   
               ////查询参数,每次调用是会带上这个参数，可自定义                         
               queryParams : function(params) {
               	var searchParam = $("#searchForm").serializeJSON();
               	searchParam.pageNo = params.limit === undefined? "1" :params.offset/params.limit+1;
               	searchParam.pageSize = params.limit === undefined? -1 : params.limit;
               	searchParam.orderBy = params.sort === undefined? "" : params.sort+ " "+  params.order;
                   return searchParam;
               },
               //分页方式：client客户端分页，server服务端分页（*）
               sidePagination: "server",
               contextMenuTrigger:"right",//pc端 按右键弹出菜单
               contextMenuTriggerMobile:"press",//手机端 弹出菜单，click：单击， press：长按。
               contextMenu: '#context-menu',
               onContextMenuItem: function(row, $el){
                   if($el.data("item") == "edit"){
                   	edit(row.id);
                   } else if($el.data("item") == "delete"){
                        jp.confirm('确认要删除该采购申请记录吗？', function(){
                       	jp.loading();
                       	jp.get("${ctx}/ap/procurementApplication/delete?id="+row.id, function(data){
                   	  		if(data.success){
                   	  			$('#procurementApplicationTable').bootstrapTable('refresh');
                   	  			jp.success(data.msg);
                   	  		}else{
                   	  			jp.error(data.msg);
                   	  		}
                   	  	})
                   	   
                   	});
                      
                   } 
               },
              
               onClickRow: function(row, $el){
               },
               columns: [{
		        checkbox: true
		       
		    },{
                   field: 'pro',
                   title: '项目',
                   sortable: true
                   ,formatter:function(value, row , index){
                       return "<a href='javascript:view(\""+row.id+"\")'>"+value+"</a>";
                   }
               }
			,{
		        field: 'bm',
		        title: '部门',
		        sortable: true

		       
		    }
			,{
		        field: 'date',
		        title: '申请日期',
		        sortable: true
		       
		    }
			,{
		        field: 'sqr',
		        title: '申请人',
		        sortable: true
		       
		    },{
                       field: 'status',
                       title: '单据状态',
                       sortable: true

                   }
                   ,{
                       field: 'cgzt',
                       title: '采购状态',
                       sortable: true

                   }
                   ,{
                       field: 'type',
                       title: '费用类型',
                       sortable: true

                   }
			,{
		        field: 'zje',
		        title: '总金额（剔税）',
		        sortable: true
		       
		    }
			,{
		        field: 'pj',
		        title: '票据类型（剔税）',
		        sortable: true
		       
		    }
			,{
		        field: 'zjehs',
		        title: '总金额（含税）',
		        sortable: true
		       
		    }
			,{
		        field: 'phhs',
		        title: '票据类型（含税）',
		        sortable: true
		       
		    }
			,{
		        field: 'cgsm',
		        title: '采购说明',
		        sortable: true
		       
		    }
			,{
		        field: 'code',
		        title: '采购申请单据号',
		        sortable: true
		       
		    }
			,{
		        field: 'gys',
		        title: '供应商及联系方式',
		        sortable: true
		       
		    }
			,{
		        field: 'cgbm',
		        title: '采购实施部门',
		        sortable: true
		       
		    }
			,{
		        field: 'ysbm',
		        title: '验收部门',
		        sortable: true
		       
		    }
                   ,{
                       field: 'cgqsr',
                       title: '采购签收人',
                       sortable: true

                   }
                   ,{
                       field: 'qssj',
                       title: '签收时间',
                       sortable: true

                   }
                   ,{
                       field: 'syfzr',
                       title: '使用负责人',
                       sortable: true

                   }

		     ]
		
		});
		
		  
	  if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端

		 
		  $('#procurementApplicationTable').bootstrapTable("toggleView");
		}
	  
	  $('#procurementApplicationTable').on('check.bs.table uncheck.bs.table load-success.bs.table ' +
                'check-all.bs.table uncheck-all.bs.table', function () {
            $('#remove').prop('disabled', $('#procurementApplicationTable').bootstrapTable('getSelections').length!=1);
          $('#bh').prop('disabled', $('#procurementApplicationTable').bootstrapTable('getSelections').length!=1);
          $('#sp').prop('disabled', $('#procurementApplicationTable').bootstrapTable('getSelections').length!=1);
          $('#qr').prop('disabled', $('#procurementApplicationTable').bootstrapTable('getSelections').length!=1);
          $('#cgqr').prop('disabled', $('#procurementApplicationTable').bootstrapTable('getSelections').length!=1);

          $('#dy').prop('disabled', $('#procurementApplicationTable').bootstrapTable('getSelections').length!=1);

          $('#edit').prop('disabled', $('#procurementApplicationTable').bootstrapTable('getSelections').length!=1);
        });
		  
		$("#btnImport").click(function(){
			jp.open({
			    type: 1, 
			    area: [500, 300],
			    title:"导入数据",
			    content:$("#importBox").html() ,
			    btn: ['下载模板','确定', '关闭'],
				    btn1: function(index, layero){
					  window.location='${ctx}/ap/procurementApplication/import/template';
				  },
			    btn2: function(index, layero){
				        var inputForm =top.$("#importForm");
				        var top_iframe = top.getActiveTab().attr("name");//获取当前active的tab的iframe 
				        inputForm.attr("target",top_iframe);//表单提交成功后，从服务器返回的url在当前tab中展示
				        inputForm.onsubmit = function(){
				        	jp.loading('  正在导入，请稍等...');
				        }
				        inputForm.submit();
					    jp.close(index);
				  },
				 
				  btn3: function(index){ 
					  jp.close(index);
	    	       }
			}); 
		});
		    
	  $("#search").click("click", function() {// 绑定查询按扭
		  $('#procurementApplicationTable').bootstrapTable('refresh');
		});
	 
	 $("#reset").click("click", function() {// 绑定查询按扭
		  $("#searchForm  input").val("");
		  $("#searchForm  select").val("");
		   $("#searchForm  .select-item").html("");
		  $('#procurementApplicationTable').bootstrapTable('refresh');
		});
		
		
	});
function cgddy(){
    if(p()=="财务已审批"){
        jp.openDialogView('打印', "${ctx}/ap/procurementApplication/dayin?id=" + getIdSelections(),'800px', '800px');
    }

}

function cgqr(){
    if(p()=="财务已审批"&&pp()=="未采购"){
        jp.openDialog('采购确认', "${ctx}/ap/procurementApplication/form1?id="+getIdSelections(),'1400px', '1000px', $('#procurementApplicationTable'));    }

}
  function getIdSelections() {
        return $.map($("#procurementApplicationTable").bootstrapTable('getSelections'), function (row) {
            return row.id
        });
    }
function p() {
    return $.map($("#procurementApplicationTable").bootstrapTable('getSelections'), function (row) {
        return row.status
    });
}
function pp() {
    return $.map($("#procurementApplicationTable").bootstrapTable('getSelections'), function (row) {
        return row.cgzt
    });
}
function qr() {
    if(p()!="已创建"&&p()!="审核未通过"){
        return;
    }
    jp.loading();
    jp.get("${ctx}/ap/procurementApplication/qr?id=" + getIdSelections(), function(data){
        if(data.success){
            $('#procurementApplicationTable').bootstrapTable('refresh');
            jp.success(data.msg);
        }else{
            jp.error(data.msg);
        }
    })
}
function  sp(ps) {

    if (getIdSelections() != null && getIdSelections() != "") {
        if(p()=="审核未通过"||p()=="已创建"){
            return;
        }
        if(p()=='总监已审批'){
            if(ps=='办事处经理'){ return;}

        }

        if(p()=='总经理已审批'){
            return;
        }
        jp.confirm('是否确认审批', function () {
           $("#tb").modal("show");
        })
    }

}
function spqd() {
   var spyj=$("#spyj").val();
    $("#tb").modal("hide");
    $("#spyj").val("");
    $.ajax({
        url: "${ctx}/ap/procurementApplication/updateStatus?id=" + getIdSelections()+"&yj="+spyj,
        data: {        //参数值
        },
        type: "post",
        success: function (data) {
            $('#procurementApplicationTable').bootstrapTable('refresh');
        },
        error: function (data) {
            alert("操作失败!");
        }
    });
}
function bh(ps) {
    if(p()=="总经理已审批"||p()=="已创建"){
        return;
    }
    if(p()=='总监已审批'){
        if(ps=='办事处经理'){ return;}

    }
    jp.confirm('是否确认驳回', function () {
        $("#tb1").modal("show");
    })

}
function bhqd() {
    var yj=$("#bhyj").val();
    $("#tb1").modal("hide");
    $("#bhyj").val("");
    $.ajax({
        url: "${ctx}/ap/procurementApplication/bh?id=" + getIdSelections()+"&yj="+yj,
        data: {        //参数值
        },
        type: "post",
        success: function (data) {
            $('#procurementApplicationTable').bootstrapTable('refresh');
        },
        error: function (data) {
            alert("操作失败!");
        }
    });
}
  function deleteAll(){
      if(p()!="已创建"&&p()!="审核未通过"){
          return;
      }
		jp.confirm('确认要删除该采购申请记录吗？', function(){
			jp.loading();  	
			jp.get("${ctx}/ap/procurementApplication/deleteAll?ids=" + getIdSelections(), function(data){
         	  		if(data.success){
         	  			$('#procurementApplicationTable').bootstrapTable('refresh');
         	  			jp.success(data.msg);
         	  		}else{
         	  			jp.error(data.msg);
         	  		}
         	  	})
          	   
		})
  }
  
  function add(){
	  jp.openDialog('新增采购申请', "${ctx}/ap/procurementApplication/form",'1400px', '1000px', $('#procurementApplicationTable'));
  }
  

function edit(id){//没有权限时，不显示确定按钮
    if(id == undefined){
        id = getIdSelections();
    }
    if(p()!="已创建"&&p()!="审核未通过"){
        return;
    }
    jp.openDialog('编辑收入', "${ctx}/ap/procurementApplication/form?id=" + id,'1000px', '800px', $('#procurementApplicationTable'));
}

function view(id) {
    jp.openDialogView('查看收入', "${ctx}/ap/procurementApplication/form?id=" + id,'1000px', '800px', $('#procurementApplicationTable'));

}
  
  
  
		   
  function detailFormatter(index, row) {
	  var htmltpl =  $("#procurementApplicationChildrenTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
	  var html = Mustache.render(htmltpl, {
			idx:row.id
		});
	  $.get("${ctx}/ap/procurementApplication/detail?id="+row.id, function(procurementApplication){
    	var procurementApplicationChild1RowIdx = 0, procurementApplicationChild1Tpl = $("#procurementApplicationChild1Tpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
		var data1 =  procurementApplication.applicationDetilList;
		for (var i=0; i<data1.length; i++){
			addRow('#procurementApplicationChild-'+row.id+'-1-List', procurementApplicationChild1RowIdx, procurementApplicationChild1Tpl, data1[i]);
			procurementApplicationChild1RowIdx = procurementApplicationChild1RowIdx + 1;
		}
          var procurementApplicationChild2RowIdx = 0, procurementApplicationChild2Tpl = $("#procurementApplicationChild2Tpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
          var data2 =procurementApplication.applicationApprovalsList;
          for (var i=0; i<data2.length; i++){
              addRow('#procurementApplicationChild-'+row.id+'-2-List', procurementApplicationChild2RowIdx, procurementApplicationChild2Tpl, data2[i]);
              procurementApplicationChild2RowIdx = procurementApplicationChild2RowIdx + 1;
          }
      })

     
        return html;
    }
  
	function addRow(list, idx, tpl, row){
		$(list).append(Mustache.render(tpl, {
			idx: idx, delBtn: true, row: row
		}));
	}
			
</script>
<script type="text/template" id="procurementApplicationChildrenTpl">//<!--
	<div class="tabs-container">
		<ul class="nav nav-tabs">
				<li class="active"><a data-toggle="tab" href="#tab-{{idx}}-1" aria-expanded="true">采购申请明细</a></li>
                               <li ><a data-toggle="tab" href="#tab-{{idx}}-2" aria-expanded="true">审批明细</a></li>

    </ul>
		<div class="tab-content">
				 <div id="tab-{{idx}}-1" class="tab-pane fade in active">
						<table class="ani table">
						<thead>
							<tr>
								<th>名称</th>
								<th>品牌型号</th>
								<th>规格/单位</th>
								<th>数量</th>
								<th>单价（剔税）</th>
								<th>总价（剔税）</th>
								<th>单价（含税）</th>
								<th>总价（含税）</th>

							</tr>
						</thead>
						<tbody id="procurementApplicationChild-{{idx}}-1-List">
						</tbody>
					</table>
				</div>
    <div id="tab-{{idx}}-2" class="tab-pane fade ">
    <table class="ani table">
    <thead>
    <tr>
    <th width="15%">操作时间</th>
    <th width="15%">操作人</th>
    <th width="15%">操作</th>
    <th width="55%">审批意见</th>
</tr>
</thead>
<tbody id="procurementApplicationChild-{{idx}}-2-List">
    </tbody>
    </table>
    </div>
		</div>//-->
	</script>
	<script type="text/template" id="procurementApplicationChild1Tpl">//<!--
				<tr>

					<td>
						{{row.mc}}
					</td>
					<td>
						{{row.pp}}
					</td>
					<td>
						{{row.gg}}
					</td>
					<td>
						{{row.sl}}
					</td>
					<td>
						{{row.dj}}
					</td>
					<td>
						{{row.zj}}
					</td>
					<td>
						{{row.djhs}}
					</td>
					<td>
						{{row.zjhs}}
					</td>


				</tr>//-->
	</script>
<script type="text/template" id="procurementApplicationChild2Tpl">//<!--
    <tr>

    <td>
    {{row.date}}
</td>
<td>
{{row.person}}
</td>
<td>
{{row.action}}
</td>
<td>
{{row.reson}}
</td>
</tr>//-->
</script>
